<template>
  <div class="cost-adjustment-container">
    <BasicInformation
      title="添加库存调拨"
      :primary-actions="actions"
      @action="handleAction"
    />

    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="120px"
    >
      <!-- 基础信息 -->
      <el-card class="form-section">
        <template #header>
          <span class="section-title">基础信息</span>
        </template>

        <el-row :gutter="30">
          <el-col :md="12">
            <el-form-item label="编号" prop="code">
              <el-input
                v-model="form.code"
                placeholder="请输入编号"
                clearable
                :disabled="true"
              />
            </el-form-item>
          </el-col>

          <el-col :md="12">
            <el-form-item label="单据日期" prop="date">
              <el-date-picker
                v-model="form.date"
                type="date"
                placeholder="请选择日期"
                value-format="YYYY-MM-DD"
                :disabled-date="disabledDate"
              />
            </el-form-item>
          </el-col>

          <el-col :md="12">
            <el-form-item label="库管员" prop="skid">
              <el-select
                v-model="form.skid"
                placeholder="请选择库管员"
                style="width: 240px"
                clearable
                filterable
              >
                <el-option
                  v-for="user in userList"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 商品清单 -->
      <el-card class="form-section">
        <template #header>
          <div class="section-header">
            <span class="section-title">商品清单</span>
            <el-button
              type="primary"
              size="small"
              @click="goodsDialogVisible = true"
            >
              添加商品
            </el-button>
          </div>
        </template>

        <el-table
          :data="form.goods"
          border
          style="width: 100%"
        >
          <el-table-column prop="code" label="商品编码" />
          <el-table-column prop="name" label="商品名称" />
          <el-table-column prop="kname" label="商品分类" />
          <el-table-column prop="uname" label="商品单位" />
          <el-table-column prop="tax" label="税率" />
          <!-- 新增：即时库存 -->
          <el-table-column label="即时库存">
            <template #default="{ $index }">
              {{ stocks[$index] }}
            </template>
          </el-table-column>
          <!-- 数量（最小1，最大库存） -->
          <el-table-column label="数量">
            <template #default="{ $index }">
              <el-input-number
                  v-model.number="form.counts[$index]"
                  :min="stocks[$index] > 0 ? 1 : 0"
                  :max="stocks[$index] ?? 0"
                  :step="1"
                  style="width: 100%"
                  @change="validateRowCount($index)"
                />
              <span v-if="stocks[$index] !== undefined" class="stock-hint">
                （当前库存：{{ stocks[$index] }}）
              </span>
            </template>
          </el-table-column>

          <el-table-column label="出仓仓库">
            <template #default="{ $index }">
              <el-select
                v-model="form.osids[$index]"
                placeholder="请选择出仓仓库"
                filterable
              >
                <el-option
                  v-for="wh in warehouses"
                  :key="wh.id"
                  :label="wh.name"
                  :value="wh.id"
                />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="入仓仓库">
            <template #default="{ $index }">
              <el-select
                v-model="form.isids[$index]"
                placeholder="请选择入仓仓库"
                filterable
              >
                <el-option
                  v-for="wh in warehouses"
                  :key="wh.id"
                  :label="wh.name"
                  :value="wh.id"
                />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 商品选择对话框 -->
      <MaterialSelectorDialog
        v-model:modelValue="form.goods"
        v-model:visible="goodsDialogVisible"
      />
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { ProMove, Good } from '@/types/kc/KCDB'
import BasicInformation from '@/public-view/BasicInformation.vue'
import MaterialSelectorDialog from '@/basic-view/bom/MaterialSelectorDialog.vue'
import type {User} from '@/types/rs/User.ts'
import request from '@/util/request'

const userInfo = sessionStorage.getItem('user');
const user = userInfo ? JSON.parse(userInfo) : null;

// 用户列表
const userList = ref<User[]>([])
async function selectUser() {
  const response = await request.post('/per/user/getAll')
  userList.value = response.data.data
}
selectUser()

// 表单数据
const form = reactive<Partial<ProMove>>({
  id: 0,
  code: '',
  date: new Date(),
  skid: 0,
  goods: [] as Good[],
  counts: [] as number[],
  osids: [] as number[],
  isids: [] as number[],
  delFlag: 0,
  typeId: 4,
  createUser: user.user.name,
  updateUser: user.user.name,
})

const formRef = ref<FormInstance>()

// 即时库存
const stocks = ref<number[]>([])

// 禁选未来日期
const disabledDate = (time: Date) => time.getTime() > Date.now()

// 校验规则
const rules = reactive<FormRules>({
  code: [{ required: true, message: '请输入编号', trigger: 'blur' }],
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  skid: [{ required: true, message: '请选择库管员', trigger: 'change' }]
})

// 加载仓库列表
const warehouses = ref<{ id: number; name: string }[]>([])
onMounted(async () => {
  try {
    const res = await request.get('basic/store/getAllStore')
    warehouses.value = res.data.data
  } catch {
    console.error('获取仓库列表失败')
  }
})

// 自动编号
async function getDocCode() {
  const res = await request.post('xs/counter/addCode', { docType: 'KCDB' })
  form.code = res.data.data
}
getDocCode()

// 弹窗
const goodsDialogVisible = ref(false)

// 初始化 goods 时重置相关数组
watch(
  () => form.goods,
  goods => {
    form.counts = goods?.map(() => 1) || []
    form.osids = goods?.map(() => 0) || []
    form.isids = goods?.map(() => 0) || []
    stocks.value = goods?.map(() => 0) || []
  },
  { deep: true }
)

// 监听 osids 变更，拉取库存
watch(
  () => form.osids.slice(),
  async osids => {
    stocks.value = await Promise.all(
      osids.map(async (osid, idx) => {
        if (!osid) return 0
        const gid = form.goods[idx].id
        const r = await request.get('kc/StoreGoodSummary/selectKcStoreGoodBySidCid', { params: { sid: osid, gid: gid } })
        return r.data.data.stock || 0
      })
    )
  },
  { immediate: true }
)

// 校验单行数量
function validateRowCount(index: number) {
  const max = stocks.value[index] || 0
  if (form.counts[index] > max) {
    ElMessage.error(`第 ${index + 1} 行数量不能超过库存 ${max}`)
    form.counts[index] = max > 0 ? max : 1
  }
}

// 操作按钮
const actions = [
  { name: 'save', label: '保存', type: 'primary' },
  { name: 'reset', label: '重置', type: 'warning' }
]

// 处理操作
function handleAction(action: string) {
  action === 'save' ? submitForm() : resetForm()
}

// 提交表单
async function submitForm() {
  // 基础校验
  if (form.counts.some(c => c < 1)) {
    ElMessage.error('所有商品的数量必须大于0')
    return
  }
  // 库存校验
  for (let i = 0; i < form.goods.length; i++) {
    if (form.counts[i] > (stocks.value[i] || 0)) {
      ElMessage.error(`第 ${i + 1} 行“${form.goods[i].name}”的调拨数量不能超过库存 ${stocks.value[i] || 0}`)
      return
    }
  }
  try {
    await formRef.value?.validate()
    const payload = JSON.parse(JSON.stringify(form))
    const resp = await request.post('kc/proMove/addProMove', payload)
    if (resp.data.code === 200 || resp.data.code === '200') {
      ElMessage.success(resp.data.message || '添加成功')
    } else {
      ElMessage.error(resp.data.message || '添加失败')
    }
  } catch {
    ElMessage.error('网络或服务异常，保存失败')
  }
}

// 重置表单
function resetForm() {
  formRef.value?.resetFields()
  form.goods = []
  form.counts = []
  form.osids = []
  form.isids = []
  stocks.value = []
  ElMessage.info('已重置表单')
}
</script>

<style scoped>
.cost-adjustment-container { padding: 20px; }
.form-section { margin-bottom: 20px; }
.section-header { display: flex; justify-content: space-between; align-items: center; }
.section-title { font-size: 16px; font-weight: 600; }
.stock-hint { margin-left: 8px; color: #999; font-size: 12px; }
</style>
